package com.douhulu.bytedance.common.redis;

import com.douhulu.bytedance.common.util.locks.JedisDistributedLock;
import lombok.RequiredArgsConstructor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.util.Pool;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * <h2> 奕泽云 -  </h2>
 *
 * @Author: 奕泽云 - 曾庆雷
 * @Email: 75881401@qq.com
 * @Since: 2022/5/1  21:38
 * CopyRight：山西威斯汀文化传播有限公司
 */
@RequiredArgsConstructor
public class JedisByteRedisOps implements ByteRedisOps {

    private final Pool<Jedis> jedisPool;

    @Override
    public String getValue(String key) {
        try (Jedis jedis = this.jedisPool.getResource()) {
            return jedis.get(key);
        }
    }

    @Override
    public void setValue(String key, String value, int expire, TimeUnit timeUnit) {
        try (Jedis jedis = this.jedisPool.getResource()) {
            if (expire <= 0) {
                jedis.set(key, value);
            } else {
                jedis.psetex(key, timeUnit.toMillis(expire), value);
            }
        }
    }

    @Override
    public Long getExpire(String key) {
        try (Jedis jedis = this.jedisPool.getResource()) {
            return jedis.ttl(key);
        }
    }

    @Override
    public void expire(String key, int expire, TimeUnit timeUnit) {
        try (Jedis jedis = this.jedisPool.getResource()) {
            jedis.pexpire(key, timeUnit.toMillis(expire));
        }
    }

    @Override
    public Lock getLock(String key) {
        return new JedisDistributedLock(jedisPool, key);
    }
}
